package com.java.basis.reflect;

import org.junit.Test;

import javax.lang.model.element.VariableElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author wangning
 * @create 2021-01-04 15:09
 */
public class TestReflect01 {

	@Test
	public void test01() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
		//获取 Person 类的 Class 对象
		Class clazz = Class.forName("com.java.basis.reflect.Person");

		//获取 Person 类的所有方法信息
		final Method[] methods = clazz.getDeclaredMethods();
		for (Method m : methods) {
			System.out.println(m);
		}

		//获取 Person 类的所有成员变量
		final Field[] declaredFields = clazz.getDeclaredFields();
		for (Field field : declaredFields) {
			System.out.println(field);
		}

		//获取 Person 类的构造方法
		final Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
		for (Constructor constructor : declaredConstructors) {
			System.out.println(constructor);
		}

		final Person person = (Person) clazz.newInstance();
		person.sleep();

	}

	@Test
	public void test02() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
		//获取 Person 类的 Class 对象
		Class clazz = Class.forName("com.java.basis.reflect.Person");

		//使用 newInstance() 方法创建对象
		final Person person = (Person) clazz.newInstance();

		//使用构造方法创建对象
		final Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class, String.class);
		//创建对象并设置属性
		final Person person1 = (Person) declaredConstructor.newInstance("张三", "男");

	}



}
